package com.ease.component.controls {
   import flash.events.Event;

   import mx.controls.TextInput;
   import mx.formatters.NumberBaseRoundType;
   import mx.formatters.NumberFormatter;

   public class NumberTextInput extends TextInput {

      private var _numberFormater:NumberFormatter = new NumberFormatter();

      private var _decimalNumber:int = 2;
      [Bindable]
      public function get decimalNumber():Number {
         return _decimalNumber;
      }
      public function set decimalNumber(value:Number):void {
         if (value <= 0) {
            _decimalNumber = 0;
            restrict = "0-9";
         }
         else {
            _decimalNumber = value;
            restrict = "0-9.";
         }
         _numberFormater.precision = _decimalNumber;
      }

      private var _rounding:String = NumberBaseRoundType.NONE;
      [Bindable]
      public function get rounding():String {
         return _rounding;
      }
      public function set rounding(value:String):void {
         _rounding = value;
         _numberFormater.rounding = _rounding;
      }

      private var _maxValue:Number = Number.MAX_VALUE;
      public function get maxValue():Number {
         return _maxValue;
      }
      public function set maxValue(value:Number):void {
         _maxValue = value;
      }

      private var _minValue:Number = Number.MIN_VALUE;
      public function get minValue():Number {
         return _minValue;
      }
      public function set minValue(value:Number):void {
         _minValue = value;
      }

      private var _value:Number = Number(text);
      [Bindable]
      public function get value():Number {
         return Number(text);
      }
      public function set value(value:Number):void {
         _value = value;
         text = isNaN(value) ? "" : formateText(value.toString());
      }

      private function textChanged(e:*):void {
         var decimalPlace:int = text.indexOf(".");
         if (decimalPlace != -1 && text.length > decimalPlace + _decimalNumber + 1) {
            text = formateText(text);
         }
         if (value > maxValue) {
            value = maxValue;
         }
         if (value < minValue) {
            value = minValue;
         }
      }

      public function NumberTextInput() {
         super();
         _numberFormater.precision = _decimalNumber;
         _numberFormater.useThousandsSeparator = false;
         _numberFormater.rounding = _rounding;
         restrict = "0-9.";
         addEventListener(Event.CHANGE, textChanged);
      }

      private function formateText(value:String):String {
         return _numberFormater.format(value);
      }
   }
}